﻿/// <reference path="jquery-1.4.2.min-vsdoc.js"/>
/// <reference path="../config/sw-config-default.js"/>
/// <reference path="../const/sw-const.js"/>
/// <reference path="sw-prototype.js"/>
/// <reference path="sw.js"/>
/// <reference path="sw-control-core.js"/>
/// <reference path="sw-controls.js"/>

$ihelper = function () {
    /// <summary>Smart UI Helper库</summary>
}

///#region 页面区域生成
$ihelper.createItemList = function (id, items, paneltype, values, isvalid, isprepend) {
    /// <summary>生成默认控件列表，如查询、编辑、查看</summary>
    /// <param name="id" type="String">需要生成区域的ID</param>
    /// <param name="items" type="Json">控件配置项集合</param>
    /// <param name="values" type="Json">数据值，会根据field赋值给控件</param>
    /// <param name="paneltype" type="String">区域类型,"edit":编辑;"search":查询;"view":查看;"viewedit":查看编辑;未设置时，为view</param>
    /// <param name="isvalid" type="Bool">是否验证,paneltype='edit' || paneltype='viewedit'时有效，默认为true</param>
    /// <param name="isprepend" type="Bool">是否在容器内容之前生成内容</param>
    var list = $('#' + id);
    if (list[0].tagName != "UL")
        list = $("<ul />").appendTo(list);

    if (!paneltype)
        paneltype = 'view';
    else if (!hasValue(isvalid) && (paneltype == 'edit' || paneltype == 'viewedit'))
        isvalid = true;
    var ctrid = id + '_';
    if (isprepend) {
        for (var i = items.length - 1; i >= 0; i--) {
            var item = items[i]
            if (typeof (item) == "object")
                $ihelper.createItem(list, ctrid, item, values, paneltype, isvalid, true);
            else
                list.prepend(item);
        }
    }
    else {
        for (var i = 0; items[i]; i++) {
            if (typeof (items[i]) == "object")
                $ihelper.createItem(list, ctrid, items[i], values, paneltype, isvalid);
            else
                list.append(items[i]);
        }
    }
    list.after(iconfig.html.common.clear);
}
$ihelper.createItem = function (panel, id, ops, values, paneltype, isvalid, isprepend) {
    /// <summary>生成控件项</summary>
    /// <param name="panel" type="JQDom">生成区域</param>
    /// <param name="id" type="id">控件ID前缀</param>
    /// <param name="ops" type="Object">控件配置项</param>
    /// <param name="values" type="Json">数据值，会根据field赋值给控件</param>
    /// <param name="paneltype" type="String">区域类型,"eidt":查询;"search":查询;"view":查看;"viewedit":查看编辑;</param>
    /// <param name="isvalid" type="Bool">是否验证</param>
    var item = $(iconfig.html.ctrItem.item).append($(iconfig.html.ctrItem.title).text(ops.name || ''));
    if (isprepend)
        panel.prepend(item);
    else
        panel.append(item);

    if (paneltype == 'viewedit') {//当不为查看编辑模式时
        paneltype = ops.viewedit ? 'edit' : 'view';
    }
    var tag, isview = paneltype == 'view';
    if (isview)//view模式时
        tag = ops.viewctr ? ops.viewctr : 'lable';
    else //设置input类型
        tag = ops.ctr == 'textarea' ? 'textarea' : 'input';

    var ctr = $(document.createElement(tag)).attr("id", id + (ops.id || ops.field));
    if (!isview) {
        ctr.attr("field", ops.field)
        if (ops.ctr == 'psd')
            ctr.attr('type', 'password');
    }
    item.append(ctr);
    if (isview)
        $ihelper.setView(ctr, ops, values);
    else {
        $ihelper.setInput(ctr, ops, values, isvalid, paneltype);

        if (paneltype != 'search' && ops.desc)
            $(iconfig.html.ctrItem.desc).text(ops.desc).appendTo(item);
    }
}
$ihelper.setInput = function (input, ops, values, isvalid, paneltype) {
    /// <summary>设置input的属性、样式、值</summary>
    /// <param name="input" type="JQDom">生成区域</param>
    /// <param name="ops" type="Object">控件配置项</param>
    /// <param name="values" type="Json">数据值，会根据field赋值给控件</param>
    /// <param name="isvalid" type="Bool">是否验证</param>
    if (values)//设置值
        input.val($ihelper.itemFormat(values, ops));
    else if (hasValue(ops.value))
        input.val(ops.value);

    ///#region 属性设置
    if (ops.ctrprop) {//设置自定义属性
        for (var name in ops.ctrprop) {
            var value = ops.ctrprop[name];
            if (hasValue(value))
                input.attr(name, value);
        }
    }
    ///#endregion

    ///#region 类型设置
    input.addClass("txt");
    var isbuilded = false;
    if (ops.type) {
        input.attr('itype', ops.type);
        switch (ops.type) {
            case "int":
            case "num":
                input.addClass("num");
                break;
            case "cur":
                input.addClass("cur");
                break;
            case "date":
            case "datetime":
                input.addClass("date");
                break;
            case "bool":
                break;
        }

        if (paneltype == 'search') {//查询模式时，范围选择
            switch (ops.type) {
                case "int":
                case "num":
                case "cur":
                    input.rangeselector({ type: 'num' });
                    isbuilded = true;
                    break;
                case "date":
                case "datetime":
                    input.rangeselector({ type: ops.type });
                    isbuilded = true;
                    break;

            }
        }
    }
    ///#endregion

    ///#region 控件初始化设置
    if (!isbuilded) {
        if (hasValue(ops.ctr)) {
            if (ops.ctr == 'textarea') {
                input.addClass('area');
            }
            else {
                switch (ops.ctr) {
                    case 'ddl':
                    case 'list':
                        input.attr('ctr', ops.ctr);
                        if (ops.ctrops) {
                            var options = { type: ops.ctr, ismulti: ops.ctrops.ismulti, ename: ops.ctrops.ename, ajax: { url: ops.ctrops.fncode} };
                            if (ops.ctr == 'ddl')
                                options.emptytype = ops.ctrops.emptytype;
                            $icontrol.chooserbydata(input, options);
                        }
                        break;
                    case 'date':
                    case 'datetime':
                        //                        if (paneltype == 'search')
                        //                            input.rangeselector({ type: 'date' });
                        //                        else
                        $icontrol.datepicker(input, { showtime: ops.ctr == 'datetime' });
                        break;
                    case 'file':
                        input = input.attr('ctr', 'file').uploader(); //返回file控件
                        break;
                }
            }
        }
    }
    ///#endregion

    ///#region 验证设置
    if (isvalid && ops.valid)
        input.initValid(ops.validops);
    ///#endregion
}
$ihelper.setView = function (ctr, ops, values) {
    /// <summary>设置View控件的属性、样式、值</summary>
    /// <param name="lbl" type="JQDom">生成区域</param>
    /// <param name="ops" type="Object">控件配置项</param>
    /// <param name="values" type="Json">数据值，会根据field赋值给控件</param>
    if (values)//设置值
        ctr.html($ihelper.itemFormat(values, ops, true));
}
$ihelper.itemFormat = function (values, ops, isview) {
    /// <summary>设置View控件的属性、样式、值</summary>
    /// <param name="values" type="Json">数据值，会根据field赋值给控件</param>
    /// <param name="ops" type="Object">控件配置项</param>
    /// <param name="isview" type="Bool">是否是查看区域</param>
    return isview ? formatStringForView(ops.type, getJsonValue(values, ops.field), ops.format)
    : formatString(ops.type, getJsonValue(values, ops.field), ops.format);
}
///#endregion
///#region 页面操作
$ihelper.openModalWithKey = function (key, paramname, uicode, width, height, modalid, title) {
    /// <summary>根据key,打开modal查看窗口</summary>
    /// <param name="key" type="Object">主键值</param>
    /// <param name="paramname" type="String">参数name</param>
    /// <param name="uicode" type="String">UI Code</param>
    /// <param name="width" type="Number">【非必要属性】，Modal窗口的宽度</param>
    /// <param name="height" type="Number">【非必要属性】，Modal窗口的高度</param>
    /// <param name="modalid" type="String">【非必要属性】，Modal窗口的ID</param>
    /// <param name="title" type="String">【非必要属性】，Modal窗口的标题</param>
    $ihelper.SetParam(paramname, key);
    $icontrol.modalwin(uicode, width, height, modalid, title);
}
$ihelper.initLoadPage = function (paramname, fncode, fninit) {
    /// <summary>根据fncode,初始化内容页面</summary>
    /// <param name="paramname" type="String">参数name</param>
    /// <param name="fncode" type="String">Function Code</param>
    /// <param name="fninit" type="Function">初始化方法</param>
    var _param = paramname ? $ihelper.GetParam(paramname) : '';
    if (hasValue(_param)) {
        var fn = function (datas) { if (fninit) { fninit((datas && datas[0]) ? datas[0] : datas); } };
        $sw.DO(fncode, _param, fn, fn);
    }
    else if (fninit)
        fninit();
}
$ihelper.search = function (fncode, searchid, listid, isrepeat) {
    /// <summary>查询操作</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="searchid" type="JQSelect">查询条件区域id选择器</param>    
    /// <param name="listid" type="JQSelect">列表选择字串id选择器</param>
    /// <param name="isrepeat" type="Bool">是否为Repeat</param>
    if (isrepeat)
        $icontrol.repeat.reload(listid, fncode, $ihelper.getJson(searchid));
    else
        $icontrol.grid.reload(listid, fncode, $ihelper.getJson(searchid));
}
$ihelper.initView = function (fncode, viewid, fninit, params, checkparam) {
    /// <summary>初始化查看页面</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="viewid" type="JQSelect">查看区域id选择器</param>    
    /// <param name="fninit" type="Function">生成后执行的方法</param>
    /// <param name="params" type="String">传递的参数</param>
    /// <param name="checkparam" type="Bool">是否判断参数为空</param>
    if (!params)
        params = $sw.globalParams.urlParams.vi;
    if (checkparam !== false && params)
        $ihelper.setViewValue(fncode, params, viewid, fninit);
}
$ihelper.save = function (fncode, editid, ismodaledit, isalert, fnsuccess, fnerror) {
    /// <summary>保存操作</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="editid" type="JQSelect">编辑区域id选择字串</param>    
    /// <param name="ismodaledit" type="Bool">【非必要属性】,是否模态窗口编辑模式，默认为true</param>
    /// <param name="isalert" type="Bool">【非必要属性】,是否使用系统提示消息</param>
    /// <param name="fnsuccess" type="function">【非必要属性】,请求成功后的操作,success（data）data:返回的值</param>
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    if ($.validArea(editid)) {
        $sw.DO(fncode, $ihelper.getJson(editid), function (data) {
            if (isalert)
                $icontrol.alert(data ? $iconst.Common.save : $iconst.Common.saveerror);
            if (fnsuccess)
                fnsuccess(data);
            if (ismodaledit !== false)
                $icontrol.modalwinClose();

        }, fnerror);
    }
}
$ihelper.gridDo = function (fncode, gridid, params, fnsuccess, fnerror, isconfirm) {
    /// <summary>Grid数据操作</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="gridid" type="String">Gird的id字串</param>    
    /// <param name="gridid" type="String">【非必要属性】,传递的参数</param>  
    /// <param name="fnsuccess" type="Function">【非必要属性】,请求成功后的操作,success（r）r:返回的值</param>
    /// <param name="fnerror" type="Function">【非必要属性】,请求失败后的操作</param>
    /// <param name="isconfirm" type="Bool">【非必要属性】,是否显示confirm提示</param>
    var fn = function () {
        if (!fnsuccess)
            fnsuccess = function () { $icontrol.grid.reload('#' + gridid); };
        $sw.DO(fncode, params, function (data) {
            $icontrol.alert(data ? $iconst.Common.operate : $iconst.Common.error);
            fnsuccess(data);
        }, fnerror);
    };
    if (isconfirm)
        $icontrol.confirm(null, fn);
    else
        fn();
}
$ihelper.gridDel = function (fncode, gridid, chkclass, fnsuccess, fnerror) {
    /// <summary>Grid控件删除操作</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="gridid" type="String">Gird的id字串</param>    
    /// <param name="chkclass" type="String">【非必要属性】,gird check的样式名</param>
    /// <param name="fnsuccess" type="function">【非必要属性】,请求成功后的操作,success（r）r:返回的值</param>
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    if (!fnsuccess)
        fnsuccess = function () { $icontrol.grid.reload('#' + gridid); };
    $ihelper.del(fncode, $ihelper.getCheckedValue(gridid, chkclass), fnsuccess, fnerror);
}
$ihelper.del = function (fncode, param, fnsuccess, fnerror) {
    /// <summary>删除操作</summary>
    /// <param name="fncode" type="String">Function Code</param>    
    /// <param name="param" type="String">传递的参数</param>    
    /// <param name="fnsuccess" type="function">【非必要属性】,请求成功后的操作,fnsuccess（r）r:返回的值</param>
    /// <param name="fnerror" type="function">【非必要属性】,请求失败后的操作</param>
    if (param) {
        $icontrol.confirm(null, function () {
            $sw.DO(fncode, param, function (data) {
                $icontrol.alert(data ? $iconst.Common.del : $iconst.Common.error);
                if (fnsuccess)
                    fnsuccess(data);
            }, fnerror);
        });
    }
    else
        $icontrol.alert($iconst.Common.delnodata);
}
$ihelper.openWinByID = function (uicode, id) {
    /// <summary>根据主键ID打开新窗口</summary>
    /// <param name="uicode" type="String">UI Code</param>    
    /// <param name="id" type="String">id值</param>    
    $sw.OpenPage(uicode, 'vi=' + id);
}
$ihelper.refreshPage = function () {
    /// <summary>刷新当前页面</summary>
    var url = window.location.href, index = url.indexOf('?'), param;
    if (index > 0) {
        url = url.substr(index);
        index = url.indexOf('u=');
        if (index > -1) {
            var endindex = url.indexOf('&', index);
            if (endindex > index)
                param = url.substr(endindex + 1);
        }
    }
    $sw.GotoPage($sw.globalParams.currentUI, param);
}
///#endregion

///#region 页面取、赋值
$ihelper.GetParam = function (name) {
    /// <summary>获取参数</summary>
    /// <param name="name" type="String">参数名</param>  
    /// <returns type="Object" />
    if (name)
        return $(iconfig.system.paramctr).data(name);
    return null;
}
$ihelper.SetParam = function (name, data) {
    /// <summary>设置参数</summary>
    /// <param name="name" type="String">参数名</param>  
    /// <param name="data" type="Object">参数值</param>  
    if (name)
        $(iconfig.system.paramctr).data(name, data ? data : null);
}
$ihelper.getJson = function (panel) {
    /// <summary>获取容器中input的json字串（根据field属性),panel为空时获取当前页面所有对象</summary>    
    /// <param name="panel" type="JQSelect">容器的选择器字串</param>
    /// <returns type="String" />
    if (panel) {
        var inputs = $(panel + " input[field]," + panel + " textarea[field]");
        var jsnValue = new StringBuilder();
        //循环拼接Json串
        inputs.each(function () {
            var txt = $(this);
            var field = txt.attr("field");
            var strValue = txt.val();
            if (strValue.length > 0) {

                var type = txt.attr('itype');
                if (type) {
                    switch (type) {//数字格式化处理
                        case 'int':
                        case 'num':
                        case 'cur':
                        case 'bool':
                            break;
                        default: // 默认已字串格式
                            strValue = '"' + getSaveText(strValue) + '"';
                            break;
                    }
                }
                else {
                    if (txt.attr('ctr') == 'file')//file时只取文件名
                        strValue = getFileName(strValue);

                    strValue = '"' + getSaveText(strValue) + '"';
                }
                jsnValue.append('"').append(txt.attr("field")).append('":').append(strValue).append(',');
            }
        });
        if (jsnValue.isNotEmpty())
            return "{" + jsnValue.strings.slice(0, -1).join("") + "}";
    }
    return '';
}


$ihelper.getJson2 = function (panel) {
    /// <summary>获取容器中input的json字串（根据field属性),panel为空时获取当前页面所有对象</summary>    
    /// <param name="panel" type="JQSelect">容器的选择器字串</param>
    /// <returns type="String" />
    if (panel) {
        var inputs = $(panel + " input[field]," + panel + " textarea[field]");
        var jsnValue = new StringBuilder();
        //循环拼接Json串
        inputs.each(function () {
            var txt = $(this);
            var field = txt.attr("field");
            var strValue = txt.val();
            if (strValue.length > 0) {

                var type = txt.attr('itype');
                if (type) {
                    switch (type) {//数字格式化处理
                        case 'int':
                        case 'num':
                        case 'cur':
                        case 'bool':
                            break;
                        default: // 默认已字串格式
                            strValue = '"' + getSaveText(strValue) + '"';
                            break;
                    }
                }
                else {
                    if (txt.attr('ctr') == 'file')//file时只取文件名
                        strValue = getFileName(strValue);

                    strValue = '"' + getSaveText(strValue) + '"';
                }
                jsnValue.append('').append(txt.attr("field")).append(':').append(strValue).append(',');
            }
        });
        if (jsnValue.isNotEmpty())
            return "{" + jsnValue.strings.slice(0, -1).join("") + "}";
    }
    return '';
}

$ihelper.setValue = function (fncode, postdata, panel, fn) {
    /// <summary>通过fncode，获取数据，然后绑定到panel区域对应的控件上</summary>
    /// <param name="fncode" type="String">Function Code</param>
    /// <param name="postdata" type="String||Json">Post Data json字串或是Json对象</param>
    /// <param name="panel" type="JQSelect">容器的选择器的字串</param>
    /// <param name="fn" type="Function">【非必要属性】,赋值完成后的操作,fn(r),r是否成功</param>
    $sw.DO(fncode, postdata, function (datas) {
        var objData;
        if (hasValue(datas)) {
            var objData = datas[0];
            var panelDom = $(panel + " input[field]," + panel + " textarea[field]");

            for (var name in objData) {//循环数据
                var value = objData[name];
                if (hasValue(value))
                    panelDom.filter("[field = '" + name + "']").val(value); //查询对应的控件赋值
            }
        }
        if (fn)
            fn(objData);
    });
}
$ihelper.setViewValue = function (fncode, postdata, panel, fn) {
    /// <summary>通过fncode，获取数据，然后绑定到panel查看区域对应的控件上</summary>
    /// <param name="fncode" type="String">Function Code</param>
    /// <param name="postdata" type="String||Json">Post Data json字串或是Json对象</param>
    /// <param name="panel" type="JQSelect">容器的选择器的字串</param>
    /// <param name="fn" type="Function">【非必要属性】,赋值完成后的操作,fn(r),r是否成功</param>
    $sw.DO(fncode, postdata, function (datas) {
        var objData;
        if (hasValue(datas)) {
            objData = datas[0];
            var panelDom = $(panel + " [field]");

            for (var name in objData) {//循环数据
                var value = objData[name];
                if (hasValue(value))
                    $ihelper.setViewCtr(panelDom.filter("[field = '" + name + "']"), value); //查询对应的控件赋值
            }
        }
        if (fn)
            fn(objData);
    });
}
$ihelper.setViewCtr = function (ctr, value) {
    /// <summary>设置view区域中控件的值</summary>
    /// <param name="ctr" type="JQDom">控件对象，JQuery对象</param>
    /// <param name="value" type="String || Number">值</param>
    if (ctr && ctr.length > 0) {
        var tag = ctr[0].tagName;
        switch (tag) {//数字格式化处理
            case "IMG":
                ctr.attr('src', getStringValue(ctr.attr('src')) + value);
                break;
            case "P":
                ctr.html(value);
                break;
            case "INPUT":
                ctr.val(formatString(ctr.attr('itype'), value, ctr.attr('format')));
                break;
            default: // 默认已字串格式
                ctr.text(formatString(ctr.attr('itype'), value, ctr.attr('format')));
                break;
        }
    }
}
$ihelper.getCheckedValue = function (containerid, chkclass, split) {
    /// <summary>获得区域内样式为chkclass选择的checkbox的值</summary>
    /// <param name="containerid" type="String">目标区域ID</param>
    /// <param name="chkclass" type="String">【非必要属性】,checkbox样式名,默认为containerid值</param>
    /// <param name="split" type="String">【非必要属性】,值之间的分割符</param>
    if (!split) split = iconfig.common.valuesplit;
    var sbValues = new StringBuilder();
    $('#' + containerid + ' input:checked.' + (chkclass || containerid)).each(function () {
        sbValues.append(this.value);
    });
    if (sbValues.isNotEmpty())
        return sbValues.toString(split || iconfig.common.valuesplit);
    return '';
}
$ihelper.getradioValue = function (containerid, name) {
    /// <summary>获得区域内属性name='name'选择的radio的值</summary>
    /// <param name="containerid" type="String">目标区域ID</param>        
    /// <param name="name" type="String">radio的name</param>
    var radio = $('#' + containerid + ' input[name="' + (name || containerid) + '"]:checked');
    if (radio.length == 1)
        return radio.val();
    return '';
}
///#endregion